package org.btik.light.mobile.common.handler.serial;

import android.view.View;
import com.hoho.android.usbserial.driver.UsbSerialPort;

import java.io.IOException;

/**
 * @author lustre
 * @since 2023/4/9 0:48
 */
public class OnClickSerialSender implements View.OnClickListener, SerialController {
    private volatile UsbSerialPort usbSerialPort;

    private final byte[] cmd;

    @Override
    public void onClick(View v) {
        if (usbSerialPort == null) {
            return;
        }
        try {
            usbSerialPort.write(cmd, 0);
        } catch (IOException e) {
            //todo notify
        }
    }

    public byte[] getCmd() {
        return cmd;
    }

    public OnClickSerialSender(byte... cmd) {
        this.cmd = new byte[cmd.length + 1];
        System.arraycopy(cmd, 0, this.cmd, 0, cmd.length);
        this.cmd[cmd.length] = '\n';
    }

    @Override
    public void bindUsbSerialPort(UsbSerialPort usbSerialPort) {
        this.usbSerialPort = usbSerialPort;
    }

    @Override
    public void disAttach() {
        this.usbSerialPort = null;
    }


}
